package com.ruoyi.stock2.thread;

import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.stock2.domain.*;
import com.ruoyi.stock2.es.CombSearchESSqlWithSimhash2;
import com.ruoyi.stock2.es.JeecgElasticsearchTemplate;
import com.ruoyi.stock2.es.SimHashUtil;
import com.ruoyi.stock2.mapper.DownTradedataScheduleMapper;
import com.ruoyi.stock2.mapper.PriceCompAverage200Mapper;
import com.ruoyi.stock2.mapper.STOCKMapper;
import com.ruoyi.stock2.service.*;
import com.ruoyi.stock2.thread.aboutDownloadData.HqSinajsServiceWithOutRedis;
import com.ruoyi.stock2.utils.EmailSend;
import com.ruoyi.stock2.utils.NameAndValue;
import com.ruoyi.stock2.utils.OtherUtils;
import com.ruoyi.stock2.utils.Sendmail;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.mail.Address;
import javax.mail.internet.InternetAddress;

public class HqSinajsThread implements Runnable {

	boolean working = false;

	String beginDateTime = "";

	HqSinajsServiceWithOutRedis hqSinajsServiceWithOutRedis;

	PriceCompAverage200Mapper priceCompareAverage200Mapper;

	DownTradedataScheduleMapper downLoadTradedataScheduleMapper;

	ISendEmailService iSendEmailService;


	//es
	STOCKMapper stockMapper;

	ITRADEDATAService itradedataService;

	ITRADEDATA200Service itradedata200Service;

	JeecgElasticsearchTemplate jeecgElasticsearchTemplate;

	IFasttextTrainService fasttextTrainService;

	ISearchFromEsService searchFromEsService;



	//count
	ISearchFromEsChooseService searchFromEsChooseService;

	ISearchFromEsIndustryService searchFromEsIndustryService;

	ISearchFromEsModelikeService searchFromEsModelikeService;
	IForetellResultService foretellResultService;

	int days = 60;
	int length = days-1;
	int scale = 2;

	public void delemysqlData(){
		LocalDate date2 = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String datestr = date2.format(formatter);
		Date date = DateUtil.parse(datestr, "yyyy-MM-dd");
		searchFromEsService.deleteSearchFromEsByDate(date);
	}

	public void queryData20andSave(){
		FasttextTrain fasttextTrain = new FasttextTrain();
		fasttextTrain.setType("type20");
		List<FasttextTrain> list1 = fasttextTrainService.selectFasttextTrainList(fasttextTrain);


		Map<String, String> map = new LinkedHashMap<>();
		Map<String, String> mapstock = new LinkedHashMap<>();

		for(int i=0; i<list1.size(); i++){
			String symbol = list1.get(i).getSymbol();
			Date date = list1.get(i).getDatetime();
			TRADEDATA tradedata = new TRADEDATA();
			tradedata.setSymbol(symbol);
			tradedata.setDatetime(date);
			List<TRADEDATA> listtrade = itradedataService.selectTradedataListForFasttextTrainModelType(tradedata);
			List<TRADEDATA200> listtradedata = new ArrayList<>(200);
			for(int j=0 ; j<listtrade.size(); j++){
				TRADEDATA200 tradedata200 = new TRADEDATA200();
				tradedata200.setSymbol(listtrade.get(j).getSymbol());
				tradedata200.setDatetime(listtrade.get(j).getDatetime());

				BeanUtils.copyProperties(listtrade.get(j), tradedata200);
				listtradedata.add(tradedata200);

			}

			if(listtradedata.size()<days*2){
				continue;
			}
			//System.out.println(i + "," + symbol + "," + date + ","+ listtradedata.size());
			if("603773 300184".contains(symbol)){
				continue;
			}
			String str1 = str51020(listtradedata);
			String str2 = strStatus(listtradedata);
			String str3 = strNear(listtradedata);
			String str4 = strAve(listtradedata);
			String[] str5 = getNear(listtradedata);

			String hashcode64 = SimHashUtil.simHashCode(str1+str2+str3+str4);

			StringBuffer stringBuffer = new StringBuffer();
			for(String str: str5){
				stringBuffer.append(str);
			}

			CombSearchESSqlWithSimhash2 combSearchESSqlWithSimhash = new CombSearchESSqlWithSimhash2();

			String json = combSearchESSqlWithSimhash.getSearchJsonhashType20(hashcode64+stringBuffer.toString(),1, 100);

			com.alibaba.fastjson.JSONObject search_jsonObject = jeecgElasticsearchTemplate.search("search_stock", "_doc", JSON.parseObject(json));

			com.alibaba.fastjson.JSONObject jsonObject = search_jsonObject.getJSONObject("hits");

			com.alibaba.fastjson.JSONArray jsonArra = jsonObject.getJSONArray("hits");

			for(int ii=0;ii<jsonArra.size();ii++){

				java.util.LinkedHashMap map1 = (java.util.LinkedHashMap)jsonArra.get(ii);
				String id = (String)map1.get("_id");

				double score = (Double)map1.get("_score");
				STOCK stock = stockMapper.selectSTOCKById(id);
				if(score>18){ //18
					String symbol1 = map.get(stock.getIndustry());
					if(mapstock.get(id)==null){
						mapstock.put(id,id);
						if(symbol1==null)
							symbol1 = "";
						map.put(stock.getIndustry(), symbol1 + " [" + id + "]");
					}

					SearchFromEs searchFromEs = new SearchFromEs();
					searchFromEs.setSymbol(stock.getSymbol());
					searchFromEs.setName(stock.getName());
					searchFromEs.setModeIdName(list1.get(i).getId() + "_" + list1.get(i).getName());
					searchFromEs.setModeType("type20");
					searchFromEs.setResultScore(score+"");
					searchFromEs.setCreateDate(new Date());
					searchFromEs.setIndustry(stock.getIndustry());
					List list = searchFromEsService.selectSearchFromEsList(searchFromEs);
					if(list.size()==0){
						searchFromEsService.insertSearchFromEs(searchFromEs);
					}




				}

			}



		}
		for (Map.Entry<String, String> entry : map.entrySet()) {
			String k = entry.getKey();
			String v = entry.getValue();
			System.out.println(k + " : " + v);
		}
	}

	public void queryData5andSave(){
		FasttextTrain fasttextTrain = new FasttextTrain();
		fasttextTrain.setType("type5");
		List<FasttextTrain> list1 = fasttextTrainService.selectFasttextTrainList(fasttextTrain);
		Map<String, String> map = new LinkedHashMap<>();
		Map<String, String> mapstock = new LinkedHashMap<>();


		for(int i=0; i<list1.size(); i++){
			String symbol = list1.get(i).getSymbol();
			Date date = list1.get(i).getDatetime();
			TRADEDATA tradedata = new TRADEDATA();
			tradedata.setSymbol(symbol);
			tradedata.setDatetime(date);
			List<TRADEDATA> listtrade = itradedataService.selectTradedataListForFasttextTrainModelType(tradedata);
			List<TRADEDATA200> listtradedata = new ArrayList<>(200);
			for(int j=0 ; j<listtrade.size(); j++){
				TRADEDATA200 tradedata200 = new TRADEDATA200();
				tradedata200.setSymbol(listtrade.get(j).getSymbol());
				tradedata200.setDatetime(listtrade.get(j).getDatetime());

				BeanUtils.copyProperties(listtrade.get(j), tradedata200);
				listtradedata.add(tradedata200);

			}

			if(listtradedata.size()<days*2){
				continue;
			}
			//System.out.println(i + "," + symbol + "," + date + ","+ listtradedata.size());
			if("603773 300184".contains(symbol)){
				continue;
			}
			String str1 = str51020(listtradedata);
			String str2 = strStatus(listtradedata);
			String str3 = strNear(listtradedata);
			String str4 = strAve(listtradedata);
			String[] str5 = getNear(listtradedata);

			String hashcode64 = SimHashUtil.simHashCode(str1+str2+str3+str4);

			StringBuffer stringBuffer = new StringBuffer();
			for(String str: str5){
				stringBuffer.append(str);
			}

			CombSearchESSqlWithSimhash2 combSearchESSqlWithSimhash = new CombSearchESSqlWithSimhash2();

			String json = combSearchESSqlWithSimhash.getSearchJsonhashType5(hashcode64+stringBuffer.toString(),1, 100);

			com.alibaba.fastjson.JSONObject search_jsonObject = jeecgElasticsearchTemplate.search("search_stock", "_doc", JSON.parseObject(json));

			com.alibaba.fastjson.JSONObject jsonObject = search_jsonObject.getJSONObject("hits");

			com.alibaba.fastjson.JSONArray jsonArra = jsonObject.getJSONArray("hits");

			for(int ii=0;ii<jsonArra.size();ii++){

				java.util.LinkedHashMap map1 = (java.util.LinkedHashMap)jsonArra.get(ii);
				String id = (String)map1.get("_id");
				double score = (Double)map1.get("_score");

				java.util.LinkedHashMap priceandDate = (java.util.LinkedHashMap)map1.get("_source");

				STOCK stock = stockMapper.selectSTOCKById(id);
				if(score>21){
					String symbol1 = map.get(stock.getIndustry());
					if(mapstock.get(id)==null){
						mapstock.put(id,id);
						if(symbol1==null)
							symbol1 = "";
						map.put(stock.getIndustry(), symbol1 + " [" + id + "]");
					}


					SearchFromEs searchFromEs = new SearchFromEs();
					searchFromEs.setSymbol(stock.getSymbol());
					searchFromEs.setName(stock.getName());
					searchFromEs.setModeIdName(list1.get(i).getId() + "_" + list1.get(i).getName());
					searchFromEs.setModeType("type5");
					searchFromEs.setResultScore(score+"");
					searchFromEs.setCreateDate(new Date());
					searchFromEs.setIndustry(stock.getIndustry());
					List list = searchFromEsService.selectSearchFromEsList(searchFromEs);
					if(list.size()==0){
						searchFromEsService.insertSearchFromEs(searchFromEs);
					}


				}

			}
		}

		for (Map.Entry<String, String> entry : map.entrySet()) {
			String k = entry.getKey();
			String v = entry.getValue();
			System.out.println(k + " : " + v);
		}
	}

	public void deleesData(){
		String json = "{\n" +
				"\t\"query\": {\n" +
				"\t\t\"match\": {\n" +
				"\t\t\t\"delflag\":\"1\"\n" +
				"\t\t}\n" +
				"\t}\n" +
				"} ";
		jeecgElasticsearchTemplate.deleteByQuery("search_stock", "_doc", com.alibaba.fastjson.JSONObject.parseObject(json));

	}

	//相似文本的demo；第一步批量插入数据；将文本hashcode后插入es
	public void saveESData() {
		jeecgElasticsearchTemplate.removeIndex("search_stock");
		//deleesData();
		JSONArray dataList = new JSONArray(500);

		List<STOCK> stocks = stockMapper.selectSTOCKList(null);
		for(int i=0; i<stocks.size(); i++){

			TRADEDATA200 tradedata200 = new TRADEDATA200();
			tradedata200.setSymbol(stocks.get(i).getSymbol());
			List<TRADEDATA200> listtradedata = itradedata200Service.get200ByKeyDateTimeDesc(tradedata200);

			if(listtradedata.size()<200){
				continue;
			}
			String str1 = str51020(listtradedata);
			String str2 = strStatus(listtradedata);
			String str3 = strNear(listtradedata);
			String str4 = strAve(listtradedata);
			String[] str5 = getNear(listtradedata);
			String hashcode64 = SimHashUtil.simHashCode(str1+str2+str3+str4);

			StringBuffer stringBuffer = new StringBuffer();
			for(String str: str5){
				stringBuffer.append(str);
			}

			CombSearchESSqlWithSimhash2 combSearchESSqlWithSimhash = new CombSearchESSqlWithSimhash2(
					listtradedata.get(0).getSymbol(), hashcode64 + stringBuffer.toString()
			);

			JSONObject json = JSONUtil.parseObj(combSearchESSqlWithSimhash, false, true);
			dataList.add(json);


			if(dataList.size()>500){
				jeecgElasticsearchTemplate.saveBatch("search_stock", "_doc", dataList);
				dataList.clear();
				System.out.println(500 + "插入完毕！");
			}



		}
		if(dataList.size()>0){
			jeecgElasticsearchTemplate.saveBatch("search_stock", "_doc", dataList);
			dataList.clear();
		}
		System.out.println("总体批量插入完毕！");
	}

	String str51020( List<TRADEDATA200> listtradedata ){

		StringBuffer stringBuffer = new StringBuffer();
		for(int m=length; m>=0; m--){
			String str5_10_20 = bijiao(listtradedata.get(m));
			stringBuffer.append("第"+(days-m)+"天五十二十").append( str5_10_20 ).append(",");

		}
		return stringBuffer.toString();
	}

	String strStatus(List<TRADEDATA200> listtradedata ){


		List<BigDecimal> lista = new ArrayList<>(40*7);
		//分析最小价格
		for(int m=length; m>=0; m--){

			BigDecimal close = listtradedata.get(m).getCloseprice();
			BigDecimal high = listtradedata.get(m).getHighprice();
			BigDecimal low = listtradedata.get(m).getLowprice();

			BigDecimal av5 = listtradedata.get(m).getAverageprice5();
			BigDecimal av10 = listtradedata.get(m).getAverageprice10();
			BigDecimal av20 = listtradedata.get(m).getAverageprice20();
			BigDecimal av60 = listtradedata.get(m).getAverageprice60();

			lista.add(close);
			lista.add(high);
			lista.add(low);
			lista.add(av5);
			lista.add(av10);
			lista.add(av20);
			lista.add(av60);

		}

		BigDecimal min = Collections.min(lista);
		//形状数据
		StringBuffer stringBuffer = new StringBuffer();
		for(int m=length; m>=0; m--){

			BigDecimal close = listtradedata.get(m).getCloseprice();
			BigDecimal high = listtradedata.get(m).getHighprice();
			BigDecimal low = listtradedata.get(m).getLowprice();

			BigDecimal av5 = listtradedata.get(m).getAverageprice5();
			BigDecimal av10 = listtradedata.get(m).getAverageprice10();
			BigDecimal av20 = listtradedata.get(m).getAverageprice20();
			BigDecimal av60 = listtradedata.get(m).getAverageprice60();

			BigDecimal minclose = close.divide(min, scale, BigDecimal.ROUND_HALF_UP);
			BigDecimal minhigh = high.divide(min, scale, BigDecimal.ROUND_HALF_UP);
			BigDecimal minlow = low.divide(min, scale, BigDecimal.ROUND_HALF_UP);

			BigDecimal minav5 = av5.divide(min, scale, BigDecimal.ROUND_HALF_UP);
			BigDecimal minav10 = av10.divide(min, scale, BigDecimal.ROUND_HALF_UP);
			BigDecimal minav20 = av20.divide(min, scale, BigDecimal.ROUND_HALF_UP);
			BigDecimal minav60 = av60.divide(min, scale, BigDecimal.ROUND_HALF_UP);

			stringBuffer.append("第"+(days-m)+"天收盘").append(minclose).append(",");
			stringBuffer.append("第"+(days-m)+"天最高").append(minhigh).append(",");
			stringBuffer.append("第"+(days-m)+"天最低").append(minlow).append(",");

			stringBuffer.append("第"+(days-m)+"天五日").append(minav5).append(",");
			stringBuffer.append("第"+(days-m)+"天十日").append(minav10).append(",");
			stringBuffer.append("第"+(days-m)+"天二十").append(minav20).append(",");
			stringBuffer.append("第"+(days-m)+"天六十").append(minav60).append(",");

			if(av5.compareTo(av10)<0){
				stringBuffer.append("第"+(days-m)+"天五日均线小于十日均线").append(",");
			}else{
                stringBuffer.append("null,");

            }

			if(av5.compareTo(av20)<0){
				stringBuffer.append("第"+(days-m)+"天五日均线小于二十日均线").append(",");
			}else{
				stringBuffer.append("null,");

			}


			if(av10.compareTo(av20)<0){
				stringBuffer.append("第"+(days-m)+"天十日均线小于二十日均线").append(",");
			}else{
				stringBuffer.append("null,");

			}
		}


		return stringBuffer.toString();
	}

	String strNear(List<TRADEDATA200> listtradedata){
		String[] nears = new String[7];
		int f = 0, e=1, d=2;

		BigDecimal closef = listtradedata.get(f).getCloseprice();
		BigDecimal av5f = listtradedata.get(f).getAverageprice5();
		BigDecimal av10f = listtradedata.get(f).getAverageprice10();
		BigDecimal av20f = listtradedata.get(f).getAverageprice20();

		BigDecimal closee = listtradedata.get(e).getCloseprice();
		BigDecimal av5e = listtradedata.get(e).getAverageprice5();
		BigDecimal av10e = listtradedata.get(e).getAverageprice10();
		BigDecimal av20e = listtradedata.get(e).getAverageprice20();

		BigDecimal closed = listtradedata.get(d).getCloseprice();
		BigDecimal av5d = listtradedata.get(d).getAverageprice5();
		BigDecimal av10d = listtradedata.get(d).getAverageprice10();
		BigDecimal av20d = listtradedata.get(d).getAverageprice20();

		if(closef.compareTo(av5f)>0){
			nears[0] = "今天收盘价格大于5日均线,";
		}else{
			nears[0] = "null,";

		}

		if(closef.compareTo(closee)>0){
			nears[1] = "今天收盘价格大于昨天收盘价格,";
		}else{
			nears[1] = "null,";

		}

		if(closef.compareTo(closed)>0){
			nears[2] = "今天收盘价格大于前天收盘价格,";
		}else{
			nears[2] = "null,";

		}


		if(closee.compareTo(closed)>0){
			nears[3] = "昨天收盘价格大于前天收盘价格,";
		}else{
			nears[3] = "null,";

		}



		nears[4] = getmin("今天收盘价距离", closef, av5f, av10f, av20f);
		nears[5] = getmin("昨天收盘价距离",closee, av5e, av10e, av20e);
		nears[6] = getmin("前天收盘价距离",closed, av5d, av10d, av20d);

		return nears[0] + nears[1] + nears[2] + nears[3] + nears[4] + nears[5] + nears[6];
	}

	String getmin(String day, BigDecimal close, BigDecimal ave5, BigDecimal ave10, BigDecimal ave20){
		BigDecimal csub5 = close.subtract(ave5).abs();
		BigDecimal csub10 = close.subtract(ave10).abs();
		BigDecimal csub20 = close.subtract(ave20).abs();

		String re = "5";
		if(csub5.compareTo(csub10)<0 && csub5.compareTo(csub20)<0){
			re = "5";
		}
		if(csub10.compareTo(csub5)<0 && csub10.compareTo(csub20)<0){
			re = "10";
		}
		if(csub20.compareTo(csub5)<0 && csub20.compareTo(csub10)<0){
			re = "20";
		}

		return day+re+"均线接近,";
	}

	String strAve(List<TRADEDATA200> listtradedata){
		String[] nears = new String[22];
		int f = 0, e=1, d=2;

		BigDecimal closef = listtradedata.get(f).getCloseprice();
		BigDecimal av5f = listtradedata.get(f).getAverageprice5();
		BigDecimal av10f = listtradedata.get(f).getAverageprice10();
		BigDecimal av20f = listtradedata.get(f).getAverageprice20();

		BigDecimal closee = listtradedata.get(e).getCloseprice();
		BigDecimal av5e = listtradedata.get(e).getAverageprice5();
		BigDecimal av10e = listtradedata.get(e).getAverageprice10();
		BigDecimal av20e = listtradedata.get(e).getAverageprice20();

		BigDecimal closed = listtradedata.get(d).getCloseprice();
		BigDecimal av5d = listtradedata.get(d).getAverageprice5();
		BigDecimal av10d = listtradedata.get(d).getAverageprice10();
		BigDecimal av20d = listtradedata.get(d).getAverageprice20();

		if(closef.compareTo(av5f)>0){
			nears[0] = "今天大于5日均线,";
		}
        else {
            nears[0] = "null,";
        }

		if(closef.compareTo(av10f)>0){
			nears[1] = "今天大于10日均线,";
		}
		else {
			nears[1] = "null,";
		}

		if(closef.compareTo(av20f)>0){
			nears[2] = "今天大于20日均线,";
		}
		else {
			nears[2] = "null,";
		}

		if(closee.compareTo(av5e)>0){
			nears[3] = "昨天大于5日均线,";
		}
		else {
			nears[3] = "null,";
		}

		if(closee.compareTo(av10e)>0){
			nears[4] = "昨天大于10日均线,";
		}
		else {
			nears[4] = "null,";
		}

		if(closee.compareTo(av20e)>0){
			nears[5] = "昨天大于20日均线,";
		}
		else {
			nears[5] = "null,";
		}

		if(closed.compareTo(av5d)>0){
			nears[6] = "前天大于5日均线,";
		}
		else {
			nears[6] = "null,";
		}

		if(closed.compareTo(av10d)>0){
			nears[7] = "前天大于10日均线,";
		}
		else {
			nears[7] = "null,";
		}

		if(closed.compareTo(av20d)>0){
			nears[8] = "前天大于20日均线,";
		}
		else {
			nears[8] = "null,";
		}

		//############################
		if(av5f.compareTo(av10f)>0){
			nears[9] = "今天5均线大于今天10日均线,";
		}
		else {
			nears[9] = "null,";
		}
		if(av5e.compareTo(av10e)>0){
			nears[10] = "昨天5均线大于昨天10日均线,";
		}
		else {
			nears[10] = "null,";
		}
		if(av5d.compareTo(av10d)>0){
			nears[11] = "前天5均线大于前天10日均线,";
		}
		else {
			nears[11] = "null,";
		}


		if(av5f.compareTo(av20f)>0){
			nears[12] = "今天5均线大于今天20日均线,";
		}
		else {
			nears[12] = "null,";
		}
		if(av5e.compareTo(av20e)>0){
			nears[13] = "昨天5均线大于昨天20日均线,";
		}
		else {
			nears[13] = "null,";
		}
		if(av5d.compareTo(av20d)>0){
			nears[14] = "前天5均线大于前天20日均线,";
		}
		else {
			nears[14] = "null,";
		}

		//########################
		if(av10f.compareTo(av20f)>0){
			nears[15] = "今天10均线大于今天20日均线,";
		}
		else {
			nears[15] = "null,";
		}
		if(av5e.compareTo(av20e)>0){
			nears[16] = "昨天10均线大于昨天20日均线,";
		}
		else {
			nears[16] = "null,";
		}
		if(av5d.compareTo(av20d)>0){
			nears[17] = "前天10均线大于前天20日均线,";
		}
		else {
			nears[17] = "null,";
		}


		BigDecimal zhangfue = listtradedata.get(e).getZhangfu();
		BigDecimal zhangfud = listtradedata.get(d).getZhangfu();

		if(zhangfue.compareTo(new BigDecimal(2))>=0){
			nears[18] = "昨天涨幅大于2,";
		}
		else {
			nears[18] = "null,";
		}
		if(zhangfud.compareTo(new BigDecimal(2))>=0){
			nears[19] = "前天涨幅大于2,";
		}
		else {
			nears[19] = "null,";
		}


		if(zhangfue.compareTo(new BigDecimal(5))>=0){
			nears[20] = "昨天涨幅大于5,";
		}
		else {
			nears[20] = "null,";
		}
		if(zhangfud.compareTo(new BigDecimal(5))>=0){
			nears[21] = "前天涨幅大于5,";
		}
		else {
			nears[21] = "null,";
		}



		return nears[0] + nears[1] + nears[2] + nears[3] + nears[4] + nears[5] + nears[6]  + nears[7] + nears[8] +

				nears[9] + nears[10] + nears[11] + nears[12] + nears[13]+ nears[14] + nears[15] + nears[16] + nears[17] +

				nears[18] + nears[19] + nears[20] + nears[21];
	}

	String bijiao(TRADEDATA200 td) {

		//BigDecimal a60 = td.getAverageprice60().setScale(2, BigDecimal.ROUND_HALF_UP);
		BigDecimal a20 = td.getAverageprice20().setScale(2, BigDecimal.ROUND_HALF_UP);
		BigDecimal a10 = td.getAverageprice10().setScale(2, BigDecimal.ROUND_HALF_UP);
		BigDecimal a5 = td.getAverageprice5().setScale(2, BigDecimal.ROUND_HALF_UP);

		List<NameAndValue> list = new ArrayList<NameAndValue>();
		list.add(new NameAndValue("5", a5));
		list.add(new NameAndValue("10", a10));
		list.add(new NameAndValue("20", a20));
		//list.add(new NameAndValue("60", a60));

		Collections.sort(list);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < list.size() - 1; i++) {
			if (list.get(i).getValue().compareTo(list.get(i + 1).getValue()) < 0) {
				sb.append(list.get(i).getName()).append("<");
			}
			if (list.get(i).getValue().compareTo(list.get(i + 1).getValue()) == 0) {
				sb.append(list.get(i).getName()).append("=");
			}
			if (list.get(i).getValue().compareTo(list.get(i + 1).getValue()) > 0) {
				sb.append(list.get(i).getName()).append(">");
			}
		}
		sb.append(list.get(list.size() - 1).getName());
		return sb.toString()

				.replace("10=5", "5=10")
				.replace("20=5", "5=20")
				.replace("60=5", "5=60")

				.replace("20=10", "10=20")
				.replace("60=10", "10=60")

				.replace("60=20", "20=60") ;

	}

	String[] getNear(List<TRADEDATA200> listtradedata){
		String[] nears = new String[18];
		int g=0, f=1, e=2, d=3, c=4, b=5;

		BigDecimal closef = listtradedata.get(f).getCloseprice();
		BigDecimal av5f = listtradedata.get(f).getAverageprice5();
		BigDecimal av10f = listtradedata.get(f).getAverageprice10();
		BigDecimal av20f = listtradedata.get(f).getAverageprice20();
		BigDecimal zhangfuf = listtradedata.get(f).getZhangfu();
		BigDecimal highf = listtradedata.get(f).getHighprice();

		BigDecimal resultf = new BigDecimal(0);
		resultf = highf.subtract(av5f).divide(av5f, 4, BigDecimal.ROUND_HALF_UP)
				.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);



		BigDecimal closee = listtradedata.get(e).getCloseprice();
		BigDecimal av5e = listtradedata.get(e).getAverageprice5();
		BigDecimal av10e = listtradedata.get(e).getAverageprice10();
		BigDecimal av20e = listtradedata.get(e).getAverageprice20();
		BigDecimal zhangfue = listtradedata.get(e).getZhangfu();
		BigDecimal highe = listtradedata.get(e).getHighprice();

		BigDecimal resulte = new BigDecimal(0);
		resulte = highe.subtract(av5e).divide(av5e, 4, BigDecimal.ROUND_HALF_UP)
				.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);



		BigDecimal closed = listtradedata.get(d).getCloseprice();
		BigDecimal av5d = listtradedata.get(d).getAverageprice5();
		BigDecimal av10d = listtradedata.get(d).getAverageprice10();
		BigDecimal av20d = listtradedata.get(d).getAverageprice20();
		BigDecimal zhangfud = listtradedata.get(d).getZhangfu();
		BigDecimal highd = listtradedata.get(d).getHighprice();

		BigDecimal resultd = new BigDecimal(0);
		resultd = highd.subtract(av5d).divide(av5d, 4, BigDecimal.ROUND_HALF_UP)
				.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);



		BigDecimal zhangfuc = listtradedata.get(c).getZhangfu();
		BigDecimal av5c = listtradedata.get(c).getAverageprice5();
		BigDecimal highc = listtradedata.get(c).getHighprice();

		BigDecimal resultc = new BigDecimal(0);
		resultc = highc.subtract(av5c).divide(av5c, 4, BigDecimal.ROUND_HALF_UP)
				.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);

		BigDecimal zhangfub = listtradedata.get(b).getZhangfu();
		BigDecimal av5b = listtradedata.get(b).getAverageprice5();
		BigDecimal highb = listtradedata.get(b).getHighprice();

		BigDecimal resultb = new BigDecimal(0);
		resultb = highb.subtract(av5b).divide(av5b, 4, BigDecimal.ROUND_HALF_UP)
				.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);

		//计算价格与5日均线的包围面积
		BigDecimal area = zhangfuf.add(zhangfue).add(zhangfud).add(zhangfuc).add(zhangfub);
		BigDecimal areb = resultf.add(resulte).add(resultd).add(resultc).add(resultb);
		//System.out.println(area.add(areb));


		BigDecimal gzf = listtradedata.get(g).getZhangfu();
		BigDecimal av5g = listtradedata.get(g).getAverageprice5();
		BigDecimal closeg = listtradedata.get(g).getCloseprice();

		if(closef.compareTo(av5f)>0){
			nears[0] = "1";
		}else {
			nears[0] = "0";
		}

		if(closee.compareTo(av5e)>0){
			nears[1] = "1";
		}else {
			nears[1] = "0";
		}

		if(closed.compareTo(av5d)>0){
			nears[2] = "1";
		}else {
			nears[2] = "0";
		}

		//##########################
		if(closef.compareTo(av20f)>0){
			nears[3] = "1";
		}else {
			nears[3] = "0";
		}

		if(closee.compareTo(av20e)>0){
			nears[4] = "1";
		}else {
			nears[4] = "0";
		}

		if(closed.compareTo(av20d)>0){
			nears[5] = "1";
		}else {
			nears[5] = "0";
		}

		//##########################
		if(av5f.compareTo(av10f)>0){
			nears[6] = "1";
		}else {
			nears[6] = "0";
		}

		if(av5e.compareTo(av10e)>0){
			nears[7] = "1";
		}else {
			nears[7] = "0";
		}

		if(av5d.compareTo(av10d)>0){
			nears[8] = "1";
		}else {
			nears[8] = "0";
		}

		//##########################
		if(av5f.compareTo(av20f)>0){
			nears[9] = "1";
		}else {
			nears[9] = "0";
		}

		if(av5e.compareTo(av20e)>0){
			nears[10] = "1";
		}else {
			nears[10] = "0";
		}

		if(av5d.compareTo(av20d)>0){
			nears[11] = "1";
		}else {
			nears[11] = "0";
		}

		//##########################
		if(av10f.compareTo(av20f)>0){
			nears[12] = "1";
		}else {
			nears[12] = "0";
		}

		if(av10e.compareTo(av20e)>0){
			nears[13] = "1";
		}else {
			nears[13] = "0";
		}

		if(av10d.compareTo(av20d)>0){
			nears[14] = "1";
		}else {
			nears[14] = "0";
		}

		if(gzf.compareTo(new BigDecimal(0))>0){//用于type5 type20
			nears[15] = "1";
		}else {
			nears[15] = "0";
		}

		if(closeg.compareTo(av5g)>0){//用于type5 不用于type20
			nears[16] = "1";
		}else {
			nears[16] = "0";
		}


		if(area.compareTo(new BigDecimal(-3.80))<=0){//用于type5 不用于type20
			nears[17] = "1";
		}else {
			nears[17] = "0";
		}

		return nears;
	}

	public void count(){
		SearchFromEs searchFromEs = new SearchFromEs();

		LocalDate date2 = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String datestr = date2.format(formatter);
		Date date = DateUtil.parse(datestr, "yyyy-MM-dd");
		//删除当天的
		searchFromEsModelikeService.deleteSearchFromEsModelikeByDate(date);
		searchFromEsIndustryService.deleteSearchFromEsIndustryByDate(date);
		searchFromEsChooseService.deleteSearchFromEsChooseByDate(date);

		searchFromEs.setCreateDate(date);
		Map<String, Long> likecount = searchFromEsService.selectModelikeCount(searchFromEs);
		Long symbolCount = likecount.get("symbolCount");


		SearchFromEsModelike searchFromEsModelike = new SearchFromEsModelike();
		searchFromEsModelike.setCreateDate(date);

		//插入当天的
		searchFromEsModelike.setSymbolCount(symbolCount);
		searchFromEsModelikeService.insertSearchFromEsModelike(searchFromEsModelike);



		List<Map<String, Object>> Industrycount = searchFromEsService.selectIndustryCount(searchFromEs);
		for(int i=0; i<Industrycount.size(); i++){
			Object industry = Industrycount.get(i).get("industry");
			Object incount = Industrycount.get(i).get("incount");
			SearchFromEsIndustry searchFromEsIndustry = new SearchFromEsIndustry();
			searchFromEsIndustry.setCreateDate(date);
			searchFromEsIndustry.setIndustry(industry.toString());
			searchFromEsIndustry.setIndustryCount(Long.parseLong(incount.toString()));
			searchFromEsIndustryService.insertSearchFromEsIndustry(searchFromEsIndustry);

			searchFromEs.setIndustry(industry.toString());
			List<Map<String, Object>> choosecount = searchFromEsService.selectChooseCount(searchFromEs);
			for(int ii=0; ii<choosecount.size(); ii++){
				Map<String, Object> map = (Map<String, Object>)choosecount.get(ii);
				Object symbol = map.get("symbol");
				Object name = map.get("name");
				Object industryii = map.get("industry");
				Object model_type = map.get("mode_type");
				Object modenumber = map.get("modenumber");
				Object maxscore = map.get("maxscore");
				Object minscore = map.get("minscore");
				Object avgscore = map.get("avgscore");

				SearchFromEsChoose searchFromEsChoose = new SearchFromEsChoose();
				searchFromEsChoose.setSymbol(symbol.toString());
				searchFromEsChoose.setName(name.toString());
				searchFromEsChoose.setIndustry(industryii.toString());
				searchFromEsChoose.setSymbolType(model_type.toString());
				searchFromEsChoose.setModeNumber(Long.parseLong(modenumber.toString()));
				searchFromEsChoose.setMaxScore(Double.parseDouble(maxscore.toString()));
				searchFromEsChoose.setMinScore(Double.parseDouble(minscore.toString()));
				searchFromEsChoose.setAvgScore(Double.parseDouble(avgscore.toString()));
				searchFromEsChoose.setCreateDate(date);
				searchFromEsChooseService.insertSearchFromEsChoose(searchFromEsChoose);
			}
		}



	}

	public StringBuffer seeold(){
		LocalDate date2 = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String datestr = date2.format(formatter);
		Date date = DateUtil.parse(datestr, "yyyy-MM-dd");

		//旧版：
		ForetellResult foretellResult = new ForetellResult();
		foretellResult.setDatetime(date);
		List<ForetellResult> frs = foretellResultService.selectForetellResult(foretellResult);
		StringBuffer stringBuffer2 = new StringBuffer();
		if(frs.size()>20){
			stringBuffer2.append("很好<br/>");
		}else {
			stringBuffer2.append("低迷<br/>");
		}


		stringBuffer2.append(
				"<table border=\"1\">\n" +
						"<tr>\n" +
						"<th style=\"width: 100px;\">日期</th>\n" +
						"<th style=\"width: 100px;\">代码</th>\n" +
						"<th style=\"width: 200px;\">名称</th>\n" +
						"<th style=\"width: 200px;\">行业</th>\n" +
						"</tr>\n");
		for(ForetellResult like : frs){
			Date cd = like.getDatetime();
			String symbol = like.getSymbol();
			String name = like.getName();
			String industry = like.getIndustry();


			stringBuffer2.append("<tr>");
			stringBuffer2.append("<td>"+ DateUtil.format(cd, "yyyy-MM-dd") +"</td>");
			stringBuffer2.append("<td>"+ symbol +"</td>");
			stringBuffer2.append("<td>"+ name +"</td>");
			stringBuffer2.append("<td>"+ industry +"</td>");

			stringBuffer2.append("</tr>\n");
		}
		stringBuffer2.append("</table>");




		return stringBuffer2;
	}

	public StringBuffer see(){
		LocalDate date2 = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String datestr = date2.format(formatter);
		Date date = DateUtil.parse(datestr, "yyyy-MM-dd");




		//新版：
		//查询近3天的
		List<SearchFromEsModelike> listModelikes = searchFromEsModelikeService.selectSearchFromEsModelikeList(null);


		List<SearchFromEsIndustry> listIndustrys0 = new ArrayList<>();
		List<SearchFromEsIndustry> listIndustrys1 = new ArrayList<>();
		List<SearchFromEsIndustry> listIndustrys2 = new ArrayList<>();

		Date cd0 = listModelikes.get(0).getCreateDate();
		SearchFromEsIndustry searchFromEsIndustry0 = new SearchFromEsIndustry();
		searchFromEsIndustry0.setCreateDate(cd0);
		listIndustrys0 = searchFromEsIndustryService.selectSearchFromEsIndustryList(searchFromEsIndustry0);

		Date cd1 = listModelikes.get(1).getCreateDate();
		SearchFromEsIndustry searchFromEsIndustry1 = new SearchFromEsIndustry();
		searchFromEsIndustry1.setCreateDate(cd1);
		listIndustrys1 = searchFromEsIndustryService.selectSearchFromEsIndustryList(searchFromEsIndustry1);

		Date cd2 = listModelikes.get(2).getCreateDate();
		SearchFromEsIndustry searchFromEsIndustry2 = new SearchFromEsIndustry();
		searchFromEsIndustry2.setCreateDate(cd2);
		listIndustrys2 = searchFromEsIndustryService.selectSearchFromEsIndustryList(searchFromEsIndustry2);


		SearchFromEsChoose searchFromEsChoose = new SearchFromEsChoose();
		searchFromEsChoose.setCreateDate(date);
		List<SearchFromEsChoose> chooses = searchFromEsChooseService.selectSearchFromEsChooseList(searchFromEsChoose);

		StringBuffer stringBuffer = new StringBuffer(
				"<table border=\"1\">\n" +
						"<tr>\n" +
						"<th style=\"width: 100px;\">日期</th>\n" +
						"<th style=\"width: 100px;\">总数量</th>\n" +
						"<th style=\"width: 100px;\">建议</th>\n" +
						"</tr>\n");
		for(SearchFromEsModelike like : listModelikes){
			Date cd = like.getCreateDate();
			Long co = like.getSymbolCount();

			stringBuffer.append("<tr>");
			stringBuffer.append("<td>"+ DateUtil.format(cd, "yyyy-MM-dd") +"</td>");
			stringBuffer.append("<td>"+ co +"</td>");
			stringBuffer.append("<td>"+ (co<=200?"观望":"不错啊") +"</td>");

			stringBuffer.append("</tr>\n");
		}
		stringBuffer.append("</table><br/>\n");

		stringBuffer.append("\n" +
				"<table border=\"1\">\n" +
				"  <tr>\n" +
				"    <th style=\"width: 100px;\">日期</th>\n" +
				"    <th style=\"width: 200px;\">行业TOP10</th>\n" +
				"    <th style=\"width: 100px;\">数量</th>\n" +

				"    <th style=\"width: 100px;\">日期</th>\n" +
				"    <th style=\"width: 200px;\">行业TOP10</th>\n" +
				"    <th style=\"width: 100px;\">数量</th>\n" +

				"    <th style=\"width: 100px;\">日期</th>\n" +
				"    <th style=\"width: 200px;\">行业TOP10</th>\n" +
				"    <th style=\"width: 100px;\">数量</th>\n" +
				"  </tr>\n");

		Map<String, Integer> inMap = new HashMap<>();

		for(int i = 0 ; i<listIndustrys0.size(); i++){
			String ina = listIndustrys0.get(i).getIndustry();
			String inb = listIndustrys1.get(i).getIndustry();
			String inc = listIndustrys2.get(i).getIndustry();
			Integer anum = inMap.get(ina);
			if(anum == null){
				inMap.put(ina, 1);
			}else {
				inMap.put(ina, 1 + anum);
			}

			Integer bnum = inMap.get(inb);
			if(bnum == null){
				inMap.put(inb, 1);
			}else {
				inMap.put(inb, 1 + bnum);
			}
			Integer cnum = inMap.get(inc);
			if(cnum == null){
				inMap.put(inc, 1);
			}else {
				inMap.put(inc, 1 + cnum);
			}


		}
		for(int i = 0 ; i<listIndustrys0.size(); i++){
			Date cda = listIndustrys0.get(i).getCreateDate();
			String ina = listIndustrys0.get(i).getIndustry();
			Long coa = listIndustrys0.get(i).getIndustryCount();

			Date cdb = listIndustrys1.get(i).getCreateDate();
			String inb = listIndustrys1.get(i).getIndustry();
			Long cob = listIndustrys1.get(i).getIndustryCount();

			Date cdc = listIndustrys2.get(i).getCreateDate();
			String inc = listIndustrys2.get(i).getIndustry();
			Long coc = listIndustrys2.get(i).getIndustryCount();

			stringBuffer.append("<tr>");
			stringBuffer.append("<td>"+ DateUtil.format(cda, "yyyy-MM-dd") +"</td>");
			if(inMap.get(ina) ==3){
				stringBuffer.append("<td style='background-color: Aquamarine ; color: blue;'>"+ ina +"</td>");
			}else if(inMap.get(ina) ==2){
				stringBuffer.append("<td style = 'background-color: Beige ; color: red;'>"+ ina +"</td>");
			} else{
				stringBuffer.append("<td>"+ ina +"</td>");
			}

			stringBuffer.append("<td>"+ coa +"</td>");

			stringBuffer.append("<td>"+ DateUtil.format(cdb, "yyyy-MM-dd") +"</td>");

			if(inMap.get(inb) ==3){
				stringBuffer.append("<td style='background-color: Aquamarine ; color: blue;'>"+ inb +"</td>");
			}else if(inMap.get(inb) ==2){
				stringBuffer.append("<td style = 'background-color: Beige ; color: red;'>"+ inb +"</td>");
			} else{
				stringBuffer.append("<td>"+ inb +"</td>");
			}

			stringBuffer.append("<td>"+ cob +"</td>");

			stringBuffer.append("<td>"+ DateUtil.format(cdc, "yyyy-MM-dd") +"</td>");
			if(inMap.get(inc) ==3){
				stringBuffer.append("<td style='background-color: Aquamarine ; color: blue;'>"+ inc +"</td>");
			}else if(inMap.get(inc) ==2){
				stringBuffer.append("<td style = 'background-color: Beige ; color: red;'>"+ inc +"</td>");
			} else{
				stringBuffer.append("<td>"+ inc +"</td>");
			}

			stringBuffer.append("<td>"+ coc +"</td>");

			stringBuffer.append("</tr>\n");
		}
		stringBuffer.append(
				"</table><br/>\n ");



		stringBuffer.append("<table border=\"1\">\n" +
				"\t<tr>\n" +
				"\t<th style=\"width: 100px;\">日期</th>\n" +
				"\t<th style=\"width: 100px;\">代码</th>\n" +
				"\t<th style=\"width: 200px;\">名称</th>\n" +
				"\t<th style=\"width: 200px;\">行业</th>\n" +
				"\t<th style=\"width: 100px;\">模型</th>\n" +
				"\t<th style=\"width: 80px;\">得票数量</th>\n" +
				"\t<th style=\"width: 80px;\">最大分数</th>\n" +
				"\t<th style=\"width: 80px;\">最小分数</th>\n" +
				"\t<th style=\"width: 80px;\">平均分数</th>\n" +
				"\t</tr>\n");
		for(SearchFromEsChoose choose : chooses){
			Date cd = choose.getCreateDate();
			String symbol = choose.getSymbol();
			String name = choose.getName();
			String in = choose.getIndustry();
			String modelType = choose.getSymbolType();
			Long number = choose.getModeNumber();

			Double max = choose.getMaxScore();

			Double min = choose.getMinScore();
			Double avg = choose.getAvgScore();



			stringBuffer.append("<tr>");
			stringBuffer.append("<td>"+ DateUtil.format(cd, "yyyy-MM-dd") +"</td>");
			stringBuffer.append("<td>"+ symbol +"</td>");
			stringBuffer.append("<td>"+ name +"</td>");

			stringBuffer.append("<td>"+ in +"</td>");
			stringBuffer.append("<td>"+ modelType +"</td>");
			stringBuffer.append("<td>"+ number +"</td>");
			stringBuffer.append("<td>"+ Double.parseDouble(String.format("%.2f",max)) +"</td>");
			stringBuffer.append("<td>"+ Double.parseDouble(String.format("%.2f",min)) +"</td>");
			stringBuffer.append("<td>"+ Double.parseDouble(String.format("%.2f",avg)) +"</td>");
			stringBuffer.append("</tr>\n");
		}

		stringBuffer.append(
				"</table>");

		return stringBuffer;
	}

	// 单例实现
	public static HqSinajsThread getInstance() {
		return Singtonle.instance;
	}

	private static class Singtonle {
		private static HqSinajsThread instance = new HqSinajsThread();
	}

	@Override
	public void run() {
		working = true;

		iSendEmailService = (ISendEmailService)SpringUtils.getBean(ISendEmailService.class);
		hqSinajsServiceWithOutRedis = (HqSinajsServiceWithOutRedis)SpringUtils.getBean(HqSinajsServiceWithOutRedis.class);
		priceCompareAverage200Mapper = (PriceCompAverage200Mapper) SpringUtils.getBean(PriceCompAverage200Mapper.class);
		downLoadTradedataScheduleMapper = (DownTradedataScheduleMapper)SpringUtils.getBean(DownTradedataScheduleMapper.class);

		stockMapper = (STOCKMapper)SpringUtils.getBean(STOCKMapper.class);
		itradedataService = (ITRADEDATAService)SpringUtils.getBean(ITRADEDATAService.class);
		itradedata200Service = (ITRADEDATA200Service)SpringUtils.getBean(ITRADEDATA200Service.class);
		jeecgElasticsearchTemplate = (JeecgElasticsearchTemplate)SpringUtils.getBean(JeecgElasticsearchTemplate.class);
		fasttextTrainService = (IFasttextTrainService)SpringUtils.getBean(IFasttextTrainService.class);
		searchFromEsService = (ISearchFromEsService)SpringUtils.getBean(ISearchFromEsService.class);

		searchFromEsChooseService = (ISearchFromEsChooseService)SpringUtils.getBean(ISearchFromEsChooseService.class);
		searchFromEsIndustryService = (ISearchFromEsIndustryService)SpringUtils.getBean(ISearchFromEsIndustryService.class);
		searchFromEsModelikeService = (ISearchFromEsModelikeService)SpringUtils.getBean(ISearchFromEsModelikeService.class);
		foretellResultService = (IForetellResultService)SpringUtils.getBean(IForetellResultService.class);

		String synchronization_sina = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("step1_synchronization_sina").getValue();
		String call_tensorflow = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("step2_call_tensorflow").getValue();
		String insert_foretell_result = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("step3_insert_foretell_result").getValue();
		String step4_pdf = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("step4_pdf").getValue();
		String send_email = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("step5_send_email").getValue();
		String download_schedule = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("download_schedule").getValue();

		/* 更新股票单 如果更新了，处在下载数据阶段，那么不再更新股票单*/
		if(!"000000".equals(download_schedule)){
			working = false;
			return;
		}

		if("1".equals(synchronization_sina)){
			priceCompareAverage200Mapper.deletePriceCompAverageByCreateDate("2000-12-12");//删除临时表记录；2000-12-12 日期是固定的
			hqSinajsServiceWithOutRedis.step1();//同步sina--tradedata201--平均值--价格比200（临时表）
		}

		if("1".equals(call_tensorflow)){
			BuildSeq2SeqPredTextThreadNew.getInstance().run();//根据临时表统计形状，调用tensorflow 深度学习模型 生成预测图片
		}

		String result = "";
		if("1".equals(insert_foretell_result)){
			result = hqSinajsServiceWithOutRedis.step2();//根据临时表统计形状插入到结果表
		}

		//新统计模型开始
		try{
			saveESData();
			String nnnn = OtherUtils.getLocalDateStr(new Date(),"HHmmss");
			delemysqlData();
			queryData20andSave();
			queryData5andSave();
			count();
		}catch (Exception e){
			e.printStackTrace();
		}

		StringBuffer stringBuffer = see();
		StringBuffer stringBuffer2 = seeold();
		if("1".equals(step4_pdf)){
			if("ok".equals(result)){
				//html2pdf();//屏幕截图并且生成pdf文件
			}
		}

		if("1".equals(send_email)){
			sendAttachmentsMail("ok", stringBuffer, stringBuffer2);
		}

		working = false;
		beginDateTime = "";
	}

	public void html2pdf(){
		try {
			String html2pdf_dir = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("html2pdf_dir").getValue();
			OtherUtils.exec("node "+html2pdf_dir+"html2pdf/stock2.js");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}


	}

	public void sendAttachmentsMail(String rusultIsnull, StringBuffer stringBuffer, StringBuffer stringBuffer2) {

		String pdf_dir = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("pred_text_dir").getValue();
		String sendEailWithExplanation = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("sendEailWithExplanation").getValue();
		SendEmail sendEmail = new SendEmail();
		sendEmail.setValid(1);//查询条件“有效”
		List<SendEmail> listSendEmail = null;
		try {
			listSendEmail = iSendEmailService.selectSendEmailListQuartz(sendEmail);

		}catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			working = false;
		}

		List<SendEmail> listSendEmail_to = new ArrayList<SendEmail>(listSendEmail.size());//收件人
		List<SendEmail> listSendEmail_bbc = new ArrayList<SendEmail>(listSendEmail.size());//密送人
		for(SendEmail sendEmail1 : listSendEmail){
			if(sendEmail1.getBcc()!=null && sendEmail1.getBcc() == 1){//等于密送标志
				listSendEmail_bbc.add(sendEmail1);
			}else{
				listSendEmail_to.add(sendEmail1);
			}
		}
		Address[] address = new Address[listSendEmail_to.size()];
		Address[] addressbbc = new Address[listSendEmail_bbc.size()];//密送

		for(int i = 0 ; i < listSendEmail_to.size() ; i++){
			try {
				address[i] = new InternetAddress(
						listSendEmail_to.get(i).getEmail(),
						listSendEmail_to.get(i).getName(),
						"UTF-8"
				);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		for(int i = 0 ; i < listSendEmail_bbc.size() ; i++){
			try {
				addressbbc[i] = new InternetAddress(
						listSendEmail_bbc.get(i).getEmail(),
						listSendEmail_bbc.get(i).getName(),
						"UTF-8"
				);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}


		if("ok".equals(rusultIsnull)){
			try {


				Sendmail.explanation = pdf_dir+"profile/pdf_files/explanation.pdf";
				Sendmail.addressbbc = addressbbc;
				Sendmail.address = address;
				Sendmail.sendEailWithExplanation = sendEailWithExplanation;

/*
				String strdate = OtherUtils.getLocalDateStr(new Date(),"yyyy-MM-dd");
				Sendmail.png = pdf_dir+"profile/pdf_files/"+"stockForecastReference"+strdate+".png";
				Sendmail.pdf = pdf_dir+"profile/pdf_files/"+"stockForecastReference"+strdate+".pdf";
				Sendmail.pdfDetails = pdf_dir+"profile/pdf_files/"+"stockForecastReferenceDetails"+strdate+".pdf";
				//判断是否生成pdf
				File fileisCreated = new File(Sendmail.pdf);
				if(!fileisCreated.exists()){
					html2pdf();
				}
				Sendmail.send();


				Sendmail.sb = stringBuffer.toString();
				Sendmail.sendDownloadDataNew();
*/

				EmailSend emailSend = new EmailSend(address, addressbbc,
						"统计报告 " + OtherUtils.getLocalDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"),
						stringBuffer.toString(), stringBuffer2.toString());

				new Thread(emailSend).start();



			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			try {
				Sendmail.sendwithoutfujian();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public boolean isWorking() {
		return working;
	}

	public void setWorking(boolean working) {
		this.working = working;
	}


	public String getBeginDateTime() {
		return beginDateTime;
	}

	public void setBeginDateTime(String beginDateTime) {
		this.beginDateTime = beginDateTime;
	}


}
